package com.wuyu.ibatis.builder;

import com.wuyu.ibatis.config.Configuration;
import com.wuyu.ibatis.session.DefaultSqlSessionFactory;
import com.wuyu.ibatis.session.SqlSessionFactory;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.InputStream;


public class SqlSessionFactoryBuilder {

    public SqlSessionFactory build(Configuration config) {
        return new DefaultSqlSessionFactory(config);
    }

    /**
     * 构建SqlSessionFactory
     * @param inputStream 配置信息
     * @return
     */
    public SqlSessionFactory build(InputStream inputStream) {
        try {
            // 1,获取DocumentBuilderFactory实例
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            // 2,获取DocumentBuilder实例
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            // 3,将docBuilder转换为Document
            Document config = docBuilder.parse(inputStream);
            //4,xml配置
            XMLConfigBuilder parser = new XMLConfigBuilder(config);
            //5,解析XML配置,构建SqlSessionFactory
            return build(parser.parse());
        } catch (Exception e) {
            throw new BuilderException(e);
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
